package com.lzk.registry.redis;

import com.lzk.domain.model.ThreadPoolConfigEntity;
import com.lzk.domain.valobj.RegistryEnumVO;
import com.lzk.registry.IRegistry;
import org.redisson.api.RBucket;
import org.redisson.api.RList;
import org.redisson.api.RedissonClient;

import java.time.Duration;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @description: 注册中心
 * @date 2025/9/9 16:42
 */
public class RedisRegistry implements IRegistry {

    private final RedissonClient redissonClient;

    public RedisRegistry(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    @Override
    public void reportThreadPool(List<ThreadPoolConfigEntity> threadPoolConfigEntites) {
        RList<ThreadPoolConfigEntity> list = redissonClient.getList(RegistryEnumVO.THREAD_POOL_CONFIG_LIST_KEY.getKey());
        Set<String> nameSet = list.stream().map(threadPoolConfigEntity -> threadPoolConfigEntity.getAppName() + "-" + threadPoolConfigEntity.getThreadPoolName()).collect(Collectors.toSet());
        for (ThreadPoolConfigEntity threadPoolConfigEntity : threadPoolConfigEntites) {
            String name = threadPoolConfigEntity.getAppName() + "-" + threadPoolConfigEntity.getThreadPoolName();
            boolean contains = nameSet.contains(name);
            if (!contains) {
                list.add(threadPoolConfigEntity);
            }
            ThreadPoolConfigEntity entity = list.stream().filter(t -> {
                String cacheName = t.getAppName() + "-" + t.getThreadPoolName();
                return cacheName.equals(name);
            }).findFirst().get();
            list.set(list.indexOf(entity), threadPoolConfigEntity);
        }
    }

    @Override
    public void reportThreadPoolConfig(ThreadPoolConfigEntity threadPoolConfigEntity) {
        String cacheKey = RegistryEnumVO.THREAD_POOL_CONFIG_PARAMETER_LIST_KEY.getKey() + "_" + threadPoolConfigEntity.getAppName() + "_" + threadPoolConfigEntity.getThreadPoolName();
        RBucket<ThreadPoolConfigEntity> bucket = redissonClient.getBucket(cacheKey);
        bucket.set(threadPoolConfigEntity, Duration.ofDays(30));
    }
}
